import { loginAPI, userInfoAPI, logoutAPI } from '@/api/account';
import { setToken, removeToken, getToken } from '@/utils/auth';

export default {
    namespaced: true,
    state: {
        token: getToken(),
        nickname: '',
        avatar: '',
        userInfo: {},
    },
    mutations: {
        SET_TOKEN(state, token) {
            state.token = token;
        },
        SET_USERINFO(state, userInfo) {
            state.nickname = userInfo.nickname;
            state.avatar = userInfo.avatar;
            state.userInfo = userInfo;
        },
        CLEAR_LOGINSTATE(state) {
            state.token = '';
            state.nickname = '';
            state.avatar = '';
            state.userInfo = {};
        },
    },
    actions: {
    /**
     * 登录action
     * @param {Object} loginParams 登录参数
     */
        async loginAction({ commit }, loginParams) {
            const result = await loginAPI(loginParams);
            const { code, data: token } = result;
            const isSuccess = code === 200;
            if (isSuccess) {
                setToken(token); // 把token保存到 cookie中
                commit('SET_TOKEN', token); // 把 token保存到vuex中
            }
            return result;
        },
        /** 获取用户信息action */
        async userInfoAction({ commit }) {
            const { code, data: userInfo } = await userInfoAPI();
            const isSuccess = code === 200;
            if (isSuccess) {
                commit('SET_USERINFO', userInfo);
            }
            return userInfo;
        },
        /** 退出登录action */
        async logoutAction({ commit }) {
            const { code } = await logoutAPI();
            const isSuccess = code === 200;
            commit('CLEAR_LOGINSTATE');
            removeToken();
            return isSuccess;
        },
    // action_end
    },
};
